package com.fowo.api.flow.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import com.fowo.api.flow.enums.flow.AssigneeTypeEnums;
import com.fowo.api.flow.model.ChildNode;
import com.fowo.api.flow.model.Properties;
import com.fowo.api.user.model.CurrentUser;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.fowo.api.flow.constant.CommonConstants.START_USER_INFO;
import static com.fowo.api.flow.utils.BpmnModelUtils.getChildNode;


/**
 * @fileName: CounterSignListener
 * @Description: 代码目的，作用，如何工作
 * @Author: pzh
 * @Date: 2023/3/27 0027 10:42
 */
@Component
public class CounterSignListener implements ExecutionListener {
    @Resource
    private RepositoryService repositoryService;

    @Override
    public void notify(DelegateExecution execution) {
        String currentActivityId = execution.getCurrentActivityId();
        Process mainProcess = repositoryService.getBpmnModel(execution.getProcessDefinitionId()).getMainProcess();
        UserTask userTask = (UserTask) mainProcess.getFlowElement(currentActivityId);
        String dingDing = mainProcess.getAttributeValue("http://flowable.org/bpmn", "DingDing");
        JSONObject jsonObject = JSONObject.parseObject(dingDing, new TypeReference<JSONObject>() {
        });
        String processJson = jsonObject.getString("processJson");
        ChildNode childNode = JSONObject.parseObject(processJson, new TypeReference<ChildNode>() {
        });
        List<String> assigneeList = new ArrayList<>();
        String variable = currentActivityId + "assigneeList";
        List usersValue = (List) execution.getVariable(variable);
        if (usersValue == null) {
            ChildNode currentNode = getChildNode(childNode, currentActivityId);
            if (currentNode == null) {
                throw new FlowableException("查找审批人失败,请联系管理员重试");
            }
            Properties props = currentNode.getProps();
            String assignedType = props.getAssignedType();
            Map<String, Object> nobody = props.getNobody();
            if (AssigneeTypeEnums.ASSIGN_USER.getTypeName().equals(assignedType)) {
                List<CurrentUser> assignedUser = props.getAssignedUser();
                for (CurrentUser userInfo : assignedUser) {
                    assigneeList.add(userInfo.getUserid());
                }
            } else if (AssigneeTypeEnums.SELF_SELECT.getTypeName().equals(assignedType)) {

            } else if (AssigneeTypeEnums.LEADER_TOP.getTypeName().equals(assignedType)) {
                throw new FlowableException("暂不做这个功能,等发版!");
            } else if (AssigneeTypeEnums.LEADER.getTypeName().equals(assignedType)) {
                throw new FlowableException("当前只是简单的系统 没有RBAC功能,各位可以自己实现!");
            } else if (AssigneeTypeEnums.ROLE.getTypeName().equals(assignedType)) {
                throw new FlowableException("当前只是简单的系统 没有RBAC功能,各位可以自己实现!");
            } else if (AssigneeTypeEnums.SELF.getTypeName().equals(assignedType)) {
                String startUserJson = execution.getVariable(START_USER_INFO, String.class);
                CurrentUser userInfo = JSONObject.parseObject(startUserJson, new TypeReference<CurrentUser>() {
                });
                assigneeList.add(userInfo.getUserid());
            } else if (AssigneeTypeEnums.FORM_USER.getTypeName().equals(assignedType)) {
                String formUser = props.getFormUser();
                List<JSONObject> assigneeUsers = execution.getVariable(formUser, List.class);
                if (assigneeUsers != null) {
                    for (JSONObject assigneeUser : assigneeUsers) {
                        assigneeList.add(assigneeUser.getString("id"));
                    }
                }

            }

            if (CollUtil.isEmpty(assigneeList)) {
                String handler = MapUtil.getStr(nobody, "handler");
                if ("TO_PASS".equals(handler)) {
                    assigneeList.add("100000");
                    execution.setVariable(variable, assigneeList);
                } else if ("TO_REFUSE".equals(handler)) {
                    execution.setVariable("autoRefuse", Boolean.TRUE);
                    assigneeList.add("100000");
                    execution.setVariable(variable, assigneeList);
                } else if ("TO_ADMIN".equals(handler)) {
                    assigneeList.add("381496");
                    execution.setVariable(variable, assigneeList);
                } else if ("TO_USER".equals(handler)) {
                    Object assignedUserObj = nobody.get("assignedUser");
                    if (assignedUserObj != null) {
                        List<JSONObject> assignedUser = (List<JSONObject>) assignedUserObj;
                        if (assignedUser.size() > 0) {
                            for (JSONObject object : assignedUser) {
                                assigneeList.add(object.getString("id"));
                            }
                            execution.setVariable(variable, assigneeList);
                        } else {
                            assigneeList.add("100000");
                            execution.setVariable(variable, assigneeList);
                        }

                    }

                } else {
                    throw new FlowableException("找不到审批人,请检查配置!!!");
                }
            } else {
                execution.setVariable(variable, assigneeList);
            }
        } else {
        }
    }
}
